﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using Stock.Dal;
using Stock.Model;

namespace Stock.Bl
{
    public class OptInputBll
    {
        private readonly StockOptHisDal stockOptHisDal = new StockOptHisDal();
        //private readonly GainHisDal gainHisDal = new GainHisDal();

        public StockOptHisEntity getGridviewData()
        {
            return null;
        }

        public List<StockOptHisEntity> getStockDataList()
        {
            DataSet ds = stockOptHisDal.GetList("", "StockInfo.S_Code ASC, StockOptHis.OptDate asc,StockOptHis.ID asc");
            return DataTableToList(ds.Tables[0]);
        }

        public void saveStockHisData(StockOptHisEntity model)
        {
            if (validateData(model))
            {
                stockOptHisDal.Add(model);
            }
            else
            {
                throw new Exception("Validate Error");
            }
        }

        private bool validateData(StockOptHisEntity model)
        {
            try
            {
                // TODO
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<StockOptHisEntity> DataTableToList(DataTable dt)
        {
            List<StockOptHisEntity> modelList = new List<StockOptHisEntity>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                StockOptHisEntity model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new StockOptHisEntity();
                    if (dt.Rows[n]["ID"] != null && dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["UserID"] != null && dt.Rows[n]["UserID"].ToString() != "")
                    {
                        model.UserID = int.Parse(dt.Rows[n]["UserID"].ToString());
                    }
                    if (dt.Rows[n]["StockID"] != null && dt.Rows[n]["StockID"].ToString() != "")
                    {
                        model.StockID = dt.Rows[n]["StockID"].ToString();
                    }
                    if (dt.Rows[n]["StockName"] != null && dt.Rows[n]["StockName"].ToString() != "")
                    {
                        model.StockName = dt.Rows[n]["StockName"].ToString();
                    }
                    if (dt.Rows[n]["Price"] != null && dt.Rows[n]["Price"].ToString() != "")
                    {
                        model.Price = decimal.Parse(dt.Rows[n]["Price"].ToString());
                    }
                    if (dt.Rows[n]["Copies"] != null && dt.Rows[n]["Copies"].ToString() != "")
                    {
                        model.Copies = int.Parse(dt.Rows[n]["Copies"].ToString());
                    }
                    if (dt.Rows[n]["Amount"] != null && dt.Rows[n]["Amount"].ToString() != "")
                    {
                        model.Amount = decimal.Parse(dt.Rows[n]["Amount"].ToString());
                    }
                    if (dt.Rows[n]["Type"] != null && dt.Rows[n]["Type"].ToString() != "")
                    {
                        model.Type = dt.Rows[n]["Type"].ToString();
                    }
                    if (dt.Rows[n]["Remark"] != null && dt.Rows[n]["Remark"].ToString() != "")
                    {
                        model.Remark = dt.Rows[n]["Remark"].ToString();
                    }
                    if (dt.Rows[n]["OptDate"] != null && dt.Rows[n]["OptDate"].ToString() != "")
                    {
                        model.OptDate = dt.Rows[n]["OptDate"].ToString();
                    }
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        internal void saveEditStockHisData(StockOptHisEntity stockOptHisEntity)
        {
            if (validateData(stockOptHisEntity))
            {
                stockOptHisDal.Update(stockOptHisEntity);
            }
            else
            {
                throw new Exception("Validate Error");
            }
        }

        /// <summary>
        /// 取得起始日期
        /// </summary>
        /// <returns></returns>
        public DateTime getMinOptDate()
        {
            string back = stockOptHisDal.GetMinDate();
            return DateTime.ParseExact(back, "yyyy-MM-dd", CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// 查询范围内进入账户的资金（大于开始日期，小于等于结束日期）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public decimal getInMoneyBeforDate(DateTime dtStart, DateTime dtEnd)
        {
            decimal back = stockOptHisDal.getInMoneyList(dtStart.ToString("yyyy-MM-dd"), dtEnd.ToString("yyyy-MM-dd"), "in");

            return back;
        }

        /// <summary>
        /// 在日期前的账户的余额（包括日期）
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public decimal getRemainingMoneyBeforDate(DateTime dt)
        {
            decimal back = stockOptHisDal.getRemainingMoneyList(dt.ToString("yyyy-MM-dd"));

            return back;
        }

        /// <summary>
        /// 取得星期五的列表
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <returns></returns>
        public List<DateTime> getFridayList(DateTime dtStart, DateTime dtEnd)
        {
            List<DateTime> back = new List<DateTime>();
            for (DateTime dt = dtStart; dt <= dtEnd; )
            {
                if (dt.DayOfWeek == DayOfWeek.Friday)
                    back.Add(dt);
                if (back.Count == 0)
                {
                    dt = dt.AddDays(1);
                }
                else
                {
                    dt = dt.AddDays(7);
                }
            }

            return back;
        }

        public void bactchCalcGain()
        {
            DateTime startDate;
            Rate rate = new Rate();

            GainHisEntity gainHisEntity = new GainHisEntity();
            //1、判断是否有历史数据（有历史数据的情况，按DB里面的数据为基准）
            if (true)
            {
                // Set Rate To LastData's Rate TODO

                startDate = DateTime.ParseExact("2011-08-01", "yyyy-MM-dd", CultureInfo.InvariantCulture);//TODO LastData's Rate;
            }
            else
            {
                startDate = getMinOptDate().AddDays(-1);
            }

            // 取得周5的列表
            List<DateTime> sd = getFridayList(startDate, DateTime.Now);

            foreach (DateTime ddt in sd)
            {
                //取得开始日期到周5的入账

                decimal inMoney = getInMoneyBeforDate(startDate, ddt);
                gainHisEntity.BankAmount = gainHisEntity.BankAmount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.BankAmount + inMoney, startDate, ddt, rate.BankRate / 100);//TODO
                gainHisEntity.BankRate = rate.BankRate;

                gainHisEntity.CalcDate = ddt.ToString("yyyy-MM-dd");

                gainHisEntity.FactSumAmount = getRemainingMoneyBeforDate(ddt) + getStockSumMoneyBeforDate(ddt);//TODO

                gainHisEntity.Pre0Amount = gainHisEntity.Pre0Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre0Amount + inMoney, startDate, ddt, rate.Pre0Rate / 100);//TODO
                gainHisEntity.Pre0 = rate.Pre0Rate;

                gainHisEntity.Pre1Amount = gainHisEntity.Pre1Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre1Amount + inMoney, startDate, ddt, rate.Pre1Rate / 100);//TODO
                gainHisEntity.Pre1 = rate.Pre1Rate;

                gainHisEntity.Pre2Amount = gainHisEntity.Pre2Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre2Amount + inMoney, startDate, ddt, rate.Pre2Rate / 100);//TODO
                gainHisEntity.Pre2 = rate.Pre2Rate;

                gainHisEntity.Pre3Amount = gainHisEntity.Pre3Amount + inMoney + Stock.Common.CaclCommon.getInterest(gainHisEntity.Pre3Amount + inMoney, startDate, ddt, rate.Pre3Rate / 100);//TODO
                gainHisEntity.Pre3 = rate.Pre3Rate;

                startDate = ddt;
            }
        }

        private decimal getStockSumMoneyBeforDate(DateTime ddt)
        {
            //取得份数不为0的股票的List
            //List<string> listStock = stockOptHisDal.getStockList(ddt.ToString("yyyy-MM-dd"));

            decimal back = 0m;
            //foreach (string stockId in listStock)
            //{
            //    string filePath = makeFilePath(stockId);
            //    decimal price = Common.CaclCommon.getStockPriceByDate(ddt.ToString("yyyy-MM-dd"), filePath);

            //    back += stockOptHisDal.getRemainingCopiesByDate(stockId, ddt.ToString("yyyy-MM-dd")) * price;
            //}
            return back;
        }

        private string makeFilePath(string stockId)
        {
            if (stockId.StartsWith("6"))
            {
                return "C:\\金鼎智赢\\T0002\\export\\SH" + stockId + ".txt";
            }
            else
            {
                return "C:\\金鼎智赢\\T0002\\export\\SZ" + stockId + ".txt";
            }
        }
    }
}